﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Behavior.Behaviors
{
    /// <summary>
    /// 大小改变时发生
    /// </summary>
    public class SizeChange:System.Windows.Interactivity.Behavior<FrameworkElement>
    {
        /// <summary> 
        /// 要附加 SizeChnage 事件的 原素 名称
        /// </summary>
        public static readonly DependencyProperty AttachSizeChnageElementProperty = DependencyProperty.Register("AttachSizeChnageElement",
             typeof(string)
                         ,
            typeof(SizeChange),
            null
             );
        /// <summary>  
        /// 要附加 SizeChnage 事件的 原素 名称
        /// </summary>
        public string AttachSizeChnageElement {
            get {


                return GetValue(AttachSizeChnageElementProperty) as string;
            }

            set{
                SetValue(AttachSizeChnageElementProperty, value);
            }


        }

        protected override void OnAttached()
        {
            base.OnAttached();
            if (AttachSizeChnageElement != null)
            {
                //大小改变时发生
                ((FrameworkElement)AssociatedObject.FindName(AttachSizeChnageElement)).SizeChanged += new SizeChangedEventHandler(AssociatedObject_SizeChanged);
            }

        }

        void AssociatedObject_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            AssociatedObject.Width = e.NewSize.Width;
            AssociatedObject.Height = e.NewSize.Height;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            if (AttachSizeChnageElement != null)
            {
                //大小改变时发生
                ((FrameworkElement)AssociatedObject.FindName(AttachSizeChnageElement)).SizeChanged -= new SizeChangedEventHandler(AssociatedObject_SizeChanged);
            }
        }
    }
}
